package com.heima.search.service.impl;

import com.heima.feigns.behavior.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Version: V1.0
 */

@Slf4j
@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    BehaviorFeign behaviorFeign;
    @Value("${file.oss.web-site}")
    String webSite;

    /**
     * 删除搜索历史
     * @param dto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto dto) {
        if (dto==null||dto.getHistoryId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        mongoTemplate.findAndRemove(Query.query(Criteria.where("id").is(dto.getHistoryId()))
                ,ApUserSearch.class);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询搜索历史    //dto變量沒有用到
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findUserSearch(UserSearchDto dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        ApBehaviorEntry byUserIdOrEquipmentId = behaviorFeign.findByUserIdOrEquipmentId(user.getId(), 0);
        if(byUserIdOrEquipmentId==null){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        List<ApUserSearch> apUserSearches = mongoTemplate.find(Query.query(
                Criteria.where("entryId").is(byUserIdOrEquipmentId.getId())
                ).with(Sort.by(Sort.Order.desc("createdTime")))
                , ApUserSearch.class);
        ResponseResult result=ResponseResult.okResult(apUserSearches);
        result.setHost(webSite);
        return result;
    }




    /**
     * 保存用户搜索历史记录
     * 异步方法
     * @param dto
     */
    @Override
    @Async
    public void insert(UserSearchDto dto) {

//        ApUser user = AppThreadLocalUtils.getUser();
//        if(user==null){
//            return;
//        }
        ApBehaviorEntry byUserIdOrEquipmentId = behaviorFeign.findByUserIdOrEquipmentId(dto.getUserID(), 0);
//        int i=1/0;
        if (byUserIdOrEquipmentId == null) {
            return;
        }

        //根据条件插入搜索记录  先查寻目前有没有
        List<ApUserSearch> apUserSearches = mongoTemplate.find(
                Query.query(Criteria.where("entryId").is(byUserIdOrEquipmentId.getId()))
                        .with(Sort.by(Sort.Order.desc("createdTime"))),
                ApUserSearch.class);

        ApUserSearch userSearch = new ApUserSearch();
        userSearch.setCreatedTime(new Date());
        userSearch.setEntryId(byUserIdOrEquipmentId.getId());
        userSearch.setKeyword(dto.getSearchWords());
        if (apUserSearches == null||apUserSearches.size()==0) {
            mongoTemplate.save(userSearch);
            return;
        }
        for (ApUserSearch apUserSearch : apUserSearches) {
            if (dto.getSearchWords().equals(apUserSearch.getKeyword())){
                mongoTemplate.findAndReplace(
                        Query.query(Criteria.where("entryId").is(byUserIdOrEquipmentId.getId())
                                .and("keyword").is(dto.getSearchWords())),apUserSearch
                );
                return;
            }
        }
        if (apUserSearches.size()>=10){
            mongoTemplate.findAndReplace(
                    Query.query(Criteria.where("entryId").is(byUserIdOrEquipmentId.getId())
                            .and("keyword").is(apUserSearches.get(apUserSearches.size()-1).getKeyword())),
                            userSearch
            );
            return;
        }
        mongoTemplate.save(userSearch);

    }
}